package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类，通知类
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    //异常类，捕获所有数据库的异常.只捕获SQL
    @ExceptionHandler(SQLException.class)
    public R<String> handlerSQLException(SQLException exception){
        String exMessage = exception.getMessage();
        log.error("[发生数据库异常]，{}",exMessage);
        if (exception.getMessage().contains("Duplicate entry")){
            String[] split = exMessage.split(" ");
            String msg = split[2] + "已存在";
            return R.error("数据库异常，不允许数据重复，"+msg);
        }else if (exMessage.contains("Data too long")){
            // 数据范围超长
            return R.error("数据库异常，数据长度超过指定范围");
        }
        return R.error("数据库未知异常");
    }

//    捕获自己定义的CustomException
    @ExceptionHandler(CustomException.class)
    public R<String> handlerRuntimeException(CustomException exception){
        String exMessage = exception.getMessage();
        log.error("[发生业务异常]，{}",exMessage);
        return R.error(exMessage);
    }
}
